package com.example.myproject.service.impl;

import com.example.myproject.dto.admin.*;
import com.example.myproject.mapper.TorrentMapper;
import com.example.myproject.mapper.UserMapper;
import com.example.myproject.model.Torrent;
import com.example.myproject.model.User;
import com.example.myproject.service.AdminService;
import com.example.myproject.service.NotificationService;
import com.example.myproject.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private TorrentMapper torrentMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private NotificationService notificationService;

    @Override
    public PendingTorrentListResponse getPendingTorrents(Integer page, Integer pageSize) {
        log.info("开始获取待审核资源列表: page={}, pageSize={}", page, pageSize);
        List<Torrent> pendingTorrents = torrentMapper.findByStatus("pending");
        log.info("查询到待审核资源数量: {}", pendingTorrents.size());

        PendingTorrentListResponse response = new PendingTorrentListResponse();
        response.setList(pendingTorrents.stream()
                .map(this::convertToPendingTorrentDTO)
                .collect(Collectors.toList()));
        response.setTotal(pendingTorrents.size());

        return response;
    }

    @Override
    @Transactional
    public ReviewResponse reviewTorrent(ReviewRequest request) {
        log.info("开始审核资源: request={}", request);

        if (request.getTorrentId() == null) {
            throw new IllegalArgumentException("资源ID不能为空");
        }

        if (request.getAction() == null) {
            throw new IllegalArgumentException("操作类型不能为空");
        }

        Torrent torrent = torrentMapper.selectById(request.getTorrentId());
        if (torrent == null) {
            log.error("资源不存在: torrentId={}", request.getTorrentId());
            throw new IllegalArgumentException("资源不存在");
        }

        if (!"pending".equals(torrent.getTorrentStatus())) {
            log.error("资源状态不正确: torrentId={}, status={}", request.getTorrentId(), torrent.getTorrentStatus());
            throw new IllegalArgumentException("该资源不在待审核状态");
        }

        if ("approve".equals(request.getAction())) {
            torrent.setTorrentStatus("normal");
            log.info("审核通过资源: torrentId={}", request.getTorrentId());
        } else if ("reject".equals(request.getAction())) {
            if (request.getReason() == null || request.getReason().trim().isEmpty()) {
                throw new IllegalArgumentException("拒绝时必须提供原因");
            }
            torrent.setTorrentStatus("violated");
            log.info("拒绝资源: torrentId={}, reason={}", request.getTorrentId(), request.getReason());
        } else {
            throw new IllegalArgumentException("无效的操作类型: " + request.getAction());
        }

        int updated = torrentMapper.updateById(torrent);
        if (updated != 1) {
            log.error("更新资源状态失败: torrentId={}", request.getTorrentId());
            throw new RuntimeException("更新资源状态失败");
        }

        // 通知上传者
        boolean notified = notificationService.notifyTorrentReview(
                torrent.getUploaderId(),
                torrent.getTorrentId(),
                request.getAction(),
                request.getReason()
        );

        ReviewResponse response = new ReviewResponse();
        response.setNotifiedUser(notified);
        response.setTorrentStatus(torrent.getTorrentStatus());

        log.info("资源审核完成: torrentId={}, status={}, notified={}",
                request.getTorrentId(), torrent.getTorrentStatus(), notified);

        return response;
    }

    private PendingTorrentDTO convertToPendingTorrentDTO(Torrent torrent) {
        PendingTorrentDTO dto = new PendingTorrentDTO();
        dto.setTorrentId(torrent.getTorrentId());
        dto.setTorrentName(torrent.getTorrentName());
        dto.setUploaderId(torrent.getUploaderId());
        dto.setUploaderName(userService.getUserInfo(torrent.getUploaderId()).getUserName());
        dto.setUploadTime(torrent.getUploadTime().toString());
        dto.setCategoryName(torrentMapper.getCategoryName(torrent.getCategoryId()));
        dto.setTorrentDescription(torrent.getTorrentDescription());
        dto.setTorrentSize(torrent.getTorrentSize());
        dto.setTorrentStatus(torrent.getTorrentStatus());
        dto.setOriginPrice(torrent.getOriginPrice());
        dto.setDownloadLimit(torrent.getDownloadLimit());
        dto.setDownloadCount(torrent.getDownloadCount());
        dto.setScore(torrent.getScore());
        dto.setMarkingCount(torrent.getMarkingCount());
        return dto;
    }

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserInfoAdminDTO> getAllUsers() {
        List<User> users = userMapper.selectAllUsersForAdmin();
        List<UserInfoAdminDTO> result = new ArrayList<>();
        for (User user : users) {
            UserInfoAdminDTO dto = new UserInfoAdminDTO();
            dto.setUserId(user.getUserId());
            dto.setUserName(user.getUserName());
            dto.setUserLevel(user.getUserLevel());
            dto.setRole(user.getRole());
            dto.setUserStatus(user.getUserStatus());
            dto.setCreatedTime(user.getCreatedTime() != null ? user.getCreatedTime().toString() : null);
            result.add(dto);
        }
        return result;
    }
    @Override
    public void updateUserLevel(Long userId, Integer level) {
        userMapper.updateUserLevel(userId, level);
    }
}